#!/bin/bash

# Sealos 一键部署脚本
# 用于将温の家项目部署到 https://bja.sealos.run/

set -e

echo "🚀 开始部署温の家项目到 Sealos..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目信息
PROJECT_NAME="wenno-app"
IMAGE_NAME="sealos.hub:5000/${PROJECT_NAME}:latest"
NAMESPACE="default"
DOMAIN="bja.sealos.run"

echo -e "${BLUE}📋 部署信息:${NC}"
echo "  项目名称: ${PROJECT_NAME}"
echo "  镜像地址: ${IMAGE_NAME}"
echo "  域名: https://${DOMAIN}"
echo "  命名空间: ${NAMESPACE}"
echo ""

# 检查必要工具
echo -e "${YELLOW}🔍 检查部署环境...${NC}"

if ! command -v docker &> /dev/null; then
    echo -e "${RED}❌ Docker 未安装，请先安装 Docker${NC}"
    exit 1
fi

if ! command -v kubectl &> /dev/null; then
    echo -e "${RED}❌ kubectl 未安装，请先安装 kubectl${NC}"
    exit 1
fi

echo -e "${GREEN}✅ 环境检查通过${NC}"

# 构建 Docker 镜像
echo -e "${YELLOW}🔨 构建 Docker 镜像...${NC}"
docker build -f Dockerfile.production -t ${IMAGE_NAME} .

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ Docker 镜像构建成功${NC}"
else
    echo -e "${RED}❌ Docker 镜像构建失败${NC}"
    exit 1
fi

# 推送镜像到 Sealos Hub
echo -e "${YELLOW}📤 推送镜像到 Sealos Hub...${NC}"
docker push ${IMAGE_NAME}

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ 镜像推送成功${NC}"
else
    echo -e "${RED}❌ 镜像推送失败${NC}"
    exit 1
fi

# 应用 Kubernetes 配置
echo -e "${YELLOW}🚀 部署到 Kubernetes...${NC}"
kubectl apply -f k8s-deployment.yaml

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ Kubernetes 部署成功${NC}"
else
    echo -e "${RED}❌ Kubernetes 部署失败${NC}"
    exit 1
fi

# 等待部署完成
echo -e "${YELLOW}⏳ 等待部署完成...${NC}"
kubectl rollout status deployment/${PROJECT_NAME} -n ${NAMESPACE} --timeout=300s

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ 部署完成${NC}"
else
    echo -e "${RED}❌ 部署超时${NC}"
    exit 1
fi

# 检查服务状态
echo -e "${YELLOW}🔍 检查服务状态...${NC}"
kubectl get pods -l app=${PROJECT_NAME} -n ${NAMESPACE}
kubectl get svc ${PROJECT_NAME}-service -n ${NAMESPACE}
kubectl get ingress ${PROJECT_NAME}-ingress -n ${NAMESPACE}

# 显示访问信息
echo ""
echo -e "${GREEN}🎉 部署成功！${NC}"
echo -e "${BLUE}📱 访问地址: https://${DOMAIN}${NC}"
echo -e "${BLUE}🔧 管理命令:${NC}"
echo "  查看 Pod 状态: kubectl get pods -l app=${PROJECT_NAME}"
echo "  查看日志: kubectl logs -l app=${PROJECT_NAME} -f"
echo "  重启服务: kubectl rollout restart deployment/${PROJECT_NAME}"
echo "  删除部署: kubectl delete -f k8s-deployment.yaml"
echo ""

# 测试健康检查
echo -e "${YELLOW}🏥 测试健康检查...${NC}"
sleep 10
if curl -s -f "https://${DOMAIN}/health" > /dev/null; then
    echo -e "${GREEN}✅ 健康检查通过${NC}"
else
    echo -e "${YELLOW}⚠️  健康检查失败，请稍后重试${NC}"
fi

echo -e "${GREEN}🎊 温の家项目已成功部署到 Sealos！${NC}"
